package com.beteng.su.betengsu.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * BitmapHelper
 * Created by maodeqiang on 2015/11/4.
 */
public class BitmapHelper {
    private static final String TAG = "BitmapHelper";
    public static int max = 0;
    public static boolean act_bool = true;
    public static List<Bitmap> bmp = new ArrayList<>();


    public static List<String> images = new ArrayList<>();

//    public static Bitmap revisionImageSize(File file) {
//        BufferedInputStream in = null;
//        try {
//            in = new BufferedInputStream(new FileInputStream(file));
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        return revisionImageSize(in);
//    }


    //图片sd地址  上传服务器时把图片调用下面方法压缩后 保存到临时文件夹 图片压缩后小于100KB，失真度不明显
    public static Bitmap revisionImageSize(File file) {
        if (file == null)
            return null;
        long start = System.currentTimeMillis();
        BufferedInputStream in = null;
        Bitmap bitmap = null;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, options);
            IOUtil.close(in);
            int i = 0;
            while (true) {
                if ((options.outWidth >> i <= 2000) && (options.outHeight >> i <= 2000)) {
                    in = new BufferedInputStream(new FileInputStream(file));
                    options.inSampleSize = (int) Math.pow(2.0D, i);
                    options.inJustDecodeBounds = false;
                    bitmap = BitmapFactory.decodeStream(in, null, options);
                    break;
                }
                i += 1;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtil.close(in);
        }
        long time = System.currentTimeMillis() - start;
        Log.d(TAG, "revisionImageSize: 耗时" + time + "毫秒");
        return bitmap;
    }

    // 图片转为文件
    public static boolean saveBitmap2file(Bitmap bmp, String filename) {
        Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
        int quality = 100;
        OutputStream stream = null;
        try {
            stream = new FileOutputStream(filename);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return bmp.compress(format, quality, stream);
    }

    // bitmap转换file
    public static File saveBitmap2file(Activity activity, Bitmap bmp) {
        if (bmp == null)
            return null;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0-100)压缩文件
        File file = new File(activity.getCacheDir(), SystemClock.currentThreadTimeMillis()+".jpg");
        IOUtil.writeTo(stream, file);
        IOUtil.close(stream);
        return file;
    }

    // uri转换bitmap
    public static Bitmap decodeUriAsBitmap(Activity activity, Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(activity.
                    getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    public static int getImageSize() {
        return images.size();
    }

    // uri转换file
    public static File decodeUriAsFile(Activity activity, Uri uri) {
        Bitmap bitmap = decodeUriAsBitmap(activity, uri);
        return saveBitmap2file(activity, bitmap);
    }

    /**
     * 自适应图片的ImageView
     * @param context
     * @param image
     * @param
     */
    public static void setImageViewMathParent(Activity context,
                                              ImageView image, Bitmap bitmap) {
        //获得屏幕密度
        DisplayMetrics displayMetrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay()
            .getMetrics(displayMetrics);
        //获得屏幕宽度和图片宽度的比例
        float scalew = (float)displayMetrics.widthPixels
            / (float) bitmap.getWidth();
        //获得ImageView的参数类
        ViewGroup.LayoutParams vgl=image.getLayoutParams();
        //设置ImageView的宽度为屏幕的宽度
        vgl.width=displayMetrics.widthPixels;
        //设置ImageView的高度
        vgl.height=(int) (bitmap.getHeight()*scalew);
        //设置图片充满ImageView控件
        image.setScaleType(ImageView.ScaleType.CENTER);
        //等比例缩放
        image.setAdjustViewBounds(true);
        image.setLayoutParams(vgl);
        image.setImageBitmap(bitmap);

        if (bitmap != null && bitmap.isRecycled()) {
            bitmap.recycle();
        }

    }


    public static Bitmap compressImageFromFile(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;//只读边,不读内容
        Bitmap bitmap;

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = 800f;//
        float ww = 480f;//
        int be = 1;
        if (w > h && w > ww) {
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置采样率

        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;//该模式是默认的,可不设
        newOpts.inPurgeable = true;// 同时设置才会有效
        newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收

        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        //      return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
        //其实是无效的,大家尽管尝试
        return bitmap;
    }

    public static byte[] getByteFromBitmap(Bitmap mp){
        ByteArrayOutputStream output = new ByteArrayOutputStream();//初始化一个流对象
        mp.compress(Bitmap.CompressFormat.JPEG, 10, output);//把bitmap100%高质量压缩 到 output对象里

        mp.recycle();//自由选择是否进行回收


        byte[] result = output.toByteArray();//转换成功了
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }



}
